<?php
namespace app\admin\controller;
use think\Controller;
use think\exception\HttpResponseException;
use think\facade\App;
use think\facade\Config;
use think\facade\Response;
use think\facade\Request;

class Base extends Controller {
    
    /**
     * @desc 用户ID
     * @var int
     */
    protected $memberId;
    
    /**
     * @desc 用户基础信息
     * @var array
     */
    protected $memberInfo = [];
    
    
    /**
     * @desc 获取用户基础信息
     */
    public function initialize() {
        //赋初始值防止模板报错
        $this->assign('memberId', $this->memberId);
        $this->assign('memberInfo', $this->memberInfo);
        
        $this->checkLogin();
    }
    
    /**
     * @desc 检测登录
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function checkLogin() {
        $this->memberId = session('memberId') ?: 0;
    
        $authAllow  = Config::get('common.admin_auth_allow');
        $controller = strtolower(Request::controller());
        $controllerAction = strtolower(Request::controller() .'/'. Request::action(true));
        if($this->memberId){
            $field = [
                'am_member_id as memberId',
                'am_username as username',
                'am_salt as salt',
                'am_group_id as groupId',
                'am_status as status',
            ];
            $this->memberInfo = App::model('AuthMember')
                ->field($field)
                ->where('am_member_id', '=', $this->memberId)
                ->find();
        
            //获取用户对应的菜单
            $memberMenu = App::model('AuthRule', 'logic')->getMemberMenu($this->memberId);
        
            $this->assign('memberId', $this->memberId);
            $this->assign('memberInfo', $this->memberInfo);
            $this->assign('memberMenu', output_format($memberMenu));
        
            //配置文件里无需验证
            if(in_array($controller, $authAllow['controller'])) {
                return true;
            }
        
            $groupId = App::model('AuthMember')
                ->where(['am_member_id' => $this->memberId, 'am_status' => AUTH_MEMBER_STATUS_YES])
                ->value('am_group_id');
        
            //如果是管理员角色组直接通过
            if($groupId == 1) {
                return true;
            }
        
            $rules = App::model('AuthGroup')->where('ag_id', '=', $groupId)->value('ag_rules');
            if(!$rules) {
                $this->authError(Config::pull('errorcode')[EC_AD_BEHAVIOR_NO_CONFIGURATION_PERMISSION]);
            }
        
            $where = [
                ['ar_id', 'in', $rules],
                ['ar_status', '=', AUTH_RULE_STATUS_YES],
            ];
            $data = App::model('AuthRule')
                ->where($where)
                ->order('ar_sort desc,ar_id asc')
                ->column('ar_controller_action');
        
            if(!in_array($controllerAction, array_map('strtolower', array_filter($data)))) {
                $this->authError(Config::pull('errorcode')[EC_AD_BEHAVIOR_NO_ACCESS_PERMISSION]);
            }
        
        }else {
            //没有检测到会话跳转到登录页面
            if(!in_array($controller, $authAllow['login'])) {
                $this->redirect(url('user/login'));
            }
        }
    }
    
    /**
     * @desc 重写视图层error操作错误跳转的快捷方法
     * @access protected
     * @param  mixed     $msg 提示信息
     * @param  string    $url 跳转的URL地址
     * @param  mixed     $data 返回的数据
     * @param  integer   $wait 跳转等待时间
     * @param  array     $header 发送的Header信息
     * @return void
     */
    protected function authError($msg = '', $url = null, $data = '', $wait = 3, array $header = []) {
        if($this->app['request']->isPost()) {
            $type = 'json';
        }else{
            $type = 'jump';
        }
        
        if (is_null($url)) {
            $url = $this->app['request']->isAjax() ? '' : 'javascript:history.back(-1);';
        } elseif ('' !== $url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app['url']->build($url);
        }
        
        if ('html' == strtolower($type)) {
            $type = 'jump';
        }
        
        if($type == 'jump') {
            $result = [
                'code' => 0,
                'msg'  => $msg,
                'data' => $data,
                'url'  => $url,
                'wait' => $wait,
            ];
        }else {
            $result = [
                'errorCode' => 0,
                'message'   => $msg,
                'data'      => $data
            ];
        }
        $response = Response::create($result, $type)->header($header)->options(['jump_template' => $this->app['config']->get('dispatch_error_tmpl')]);
        throw new HttpResponseException($response);
    }
}
